package com.freesun.shop.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.service.CategoryService;
import com.freesun.shop.entity.Category;
import com.freesun.shop.mapper.CategoryMapper;

import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 产品类目 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
@CacheConfig(cacheNames = "com.freesun.shop.entity.Category")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Override
    public boolean removeById(Serializable id) {
        logger.info("删除分类,{}",id);
        Category category = this.baseMapper.selectById(id);
        if (null == category) {
            throw new RuntimeException("要删除的数据不存在");
        }
        //有子节点则不能删除
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, id));
        if(count!=null&&count>0){
            throw new RuntimeException("要删除的分类菜单有子节点");
        }
        return super.removeById(id);
    }

    @Override
    public List<Category> listParent() {
        logger.info("查询所有的父节点");
        List<Category> list = this.baseMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0L)
                .eq(Category::getStatus, 1));
        return list;
    }

    @Override
    @CacheEvict(allEntries = true,key = "'subNodes:'")
    public boolean save(Category entity) {
        logger.info("新增一个商品分类,分类名称:{}",entity.getCategoryName());
        Assert.notNull(entity,"新增的分类不能为Null");
        if (entity.getParentId() == null || entity.getParentId() == 0L) { //代表为1级节点
            entity.setCategoryId(0L);
            entity.setGrade(1);
        }else {
            entity.setGrade(2);
        }
        entity.setRecTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        return super.save(entity);
    }

    /**
     * 微信小程序，,通过父ID查询子菜单
     * @param parentId
     * @return
     */
    @Override
    @Cacheable(key = "'subNodes:'(#parentId)")
    public List<Category> getSubNodes(Long parentId) {
        Assert.notNull(parentId,"父ID不能为Null");
        logger.info("查询的父ID为:{}", parentId);
        return this.baseMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, parentId));
    }
}
